import config from './config/config'
import utils from 'ts-element/packages/utils/utils'
import VueCookies from 'vue-cookies'
import CryptoJS from 'crypto-js'
const obj = {
        set(keyname, value, time, path, domain, secure) {
            let val = value
            if (value) {
                val = this.encrypt(value)
            }
            if (config.isEncrypt) {
                val += '.ts'
            }
            return VueCookies.set(keyname, val, time, path, domain, secure, true)
        },
        get(keyname) {
            let val = VueCookies.get(keyname)
            if (val) {
                if (config.isEncrypt && val.indexOf('.ts') > -1) {
                    val = val.split('.ts')[0]
                }
                return this.decrypt(val)
            } else {
                return val
            }
        },
        remove(keyname, path, domain) {
            return VueCookies.remove(keyname, path, domain)
        },
        encrypt(word, mode, keystr) {
            if (!config.isEncrypt) {
                return word
            }
            let key = utils.md5Key(keystr || '')
            let kv = utils.splitKeyAnIv(key)
            let _word = CryptoJS.enc.Utf8.parse(word)
            let _key = CryptoJS.enc.Utf8.parse(kv[0])
            let _iv = CryptoJS.enc.Utf8.parse(kv[1])
            let encrypted = CryptoJS.AES.encrypt(_word, _key, {
                iv: _iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            })
            mode = (mode == 1 || mode == undefined) ? 1 : 0
            if (mode == 1) {
                //16进制输出
                return encrypted.ciphertext.toString()
            } else {
                //默认base64输出
                return encrypted.toString()
            }
        },
        // 解密
        decrypt(str, mode) {
            if (!config.isEncrypt) {
                return str
            }
            return this.aesDecrypt(str, mode)
        },
        // 解密
        aesDecrypt(str, mode) {
            var kv = utils.splitKeyAnIv(utils.md5Key(''))
            let _key = CryptoJS.enc.Utf8.parse(kv[0])
            let _iv = CryptoJS.enc.Utf8.parse(kv[1])
            let ww = str
            mode = mode == 1 ? 1 : 0
            if (mode == 0) {
                // 16进制
                ww = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(str))
            }
            var decrypted = CryptoJS.AES.decrypt(ww, _key, {
                iv: _iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
            return decrypted.toString(CryptoJS.enc.Utf8)
        }
    }
    // 加密

export default obj